package com.ruoyi.framework.wx.handle;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Component
public class UnSubscribeHandler implements WxMpMessageHandler {
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		String lang = "zh_CN";
		String wxId = wxMessage.getToUser();
		WxMpUser user = wxMpService.getUserService().userInfo(wxMessage.getFromUser(), lang);
		
		if(StringUtils.isNotBlank(user.getUnionId())){
			List<SysUser> userList = sysUserService.getUserByUnionId(wxId,user.getUnionId());
			
			for(SysUser sysUser : userList){
				sysUser.setWxOpenId(user.getOpenId());
				sysUserService.updateWxOpenId(sysUser);
			}
		}
		
		return WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
				.content("取消关注").build();
	}
	
	

}
